
import Const  from '@/utils/const.js'
const baseURL=Const.baseURL

/**
 * 将对象转成 a=1&b=2的查询参数形式
 * @param obj 对象
 */
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

/**
 * 请求封装
 * @param url
 * @param params
 * @param method
 * @returns {Promise<unknown>}
 */
export default (url, params, method = 'GET') => {
  return new Promise((resolve, reject) => {
    let initObj = {
      method: method,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
    if (method.toUpperCase() === 'GET') {
      const searchStr = obj2String(params)
      // GET请求，拼接url
      if (searchStr) {
        url += '?' + searchStr
      }
    } else {
      //POST或PUT或DELETE请求  增加 application/json
      Object.assign(initObj.headers, {
        'Content-Type': 'application/json;charset=utf-8',
        'X-Custom-Token': localStorage.getItem(Const.ACCESS_TOKEN)
      })
      initObj = {
        ...initObj,
        body: JSON.stringify(params)
      }
    }
    console.log(initObj)
    fetch(baseURL + url, initObj)
      .then((res) => res.json())
      .then((res) => {
        switch (res.code) {
          case 200:
            // console.log('成功了')
            resolve(res.data)
            break
          default: {
            // reject(res.message)
            alert(res.message)
          }
        }
      })
      .catch((err) => {
        console.log(err)
        alert('网络请求异常')
      })
  })
}
